package com.yitiao.service;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.yitiao.entity.CommerceUser;
import com.yitiao.event.UserAddEvent;
import com.yitiao.mapper.CommerceUserMapper;
import com.yitiao.service.ds.UserDsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {
    private final CommerceUserMapper userMapper;

    private final ApplicationEventPublisher eventPublisher;

    private final UserDsService userDsService;

    private final AsyncService asyncService;

    public CommerceUser getUserById(String id) {
        asyncService.run();
//        int a = 1/0;
//        sleepRandom();

//        return Long.parseLong(id) % 2 == 0
//                ? userDsService.getUserByIdWithDbKey0(id)
//                : userDsService.getUserByIdWithDbKey1(id);

//        DataSourceHandler.changeDataSource(MultiDataSource.SALVE_ZERO_DATA_SOURCE);

        log.info("select datasource ... ");
        DynamicDataSourceContextHolder.push(String.format("slave%s", Long.parseLong(id) % 2));
        CommerceUser user = userMapper.selectById(id);
        DynamicDataSourceContextHolder.clear();

        return user;
    }

    private void sleepRandom() {
        //随机睡眠毫秒数
        int sleepSeconds = (int) (Math.random() * 1000);
        try {
            TimeUnit.MILLISECONDS.sleep(sleepSeconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void addUser(CommerceUser user) {
        userMapper.insert(user);
        eventPublisher.publishEvent(new UserAddEvent("new user:"+user.getUsername()));
    }
}
